<template>
  <div class="min-h-screen bg-gray-50">
    <div class="px-4 pt-4">
      <nav class="text-sm text-gray-500 flex items-center space-x-2">
        <NuxtLink to="/" class="text-blue-600 hover:underline">首页</NuxtLink>
        <span>/</span>
        <span class="text-gray-700">协议签署</span>
      </nav>
    </div>
    <!-- 页面标题 -->
    <div class="text-center py-6">
      <h1 class="text-xl font-medium text-gray-900">协议签署</h1>
    </div>

    <!-- 表单内容 -->
    <div v-if="latestApplicationApproved" class="p-6 text-center">
      <div class="text-xl font-semibold text-green-600 mb-4">您已成功签约该任务。</div>
      <div class="text-gray-600">可以在<strong>签约记录</strong>中查看详情。</div>
      <button
        type="button"
        class="mt-6 px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600"
        @click="navigateTo('/contracts')"
      >
        查看签约记录
      </button>
    </div>

    <div v-else class="p-4">
      <div class="space-y-6">
        <div
          :class="[
            'collapse rounded-lg',
            !isVerified ? 'collapse-open collapse-arrow bg-white' : 'collapse-close bg-gray-100'
          ]"
        >
          <input type="checkbox" class="peer" :checked="!isVerified" />
          <div class="collapse-title text-base font-medium text-gray-900">
            步骤一：四要素认证
          </div>
          <div
            class="collapse-content space-y-4"
            v-if="!isVerified"
            :style="!isVerified ? { height: 'fit-content' } : undefined"
          >
            <div class="bg-orange-50 border-l-4 border-orange-400 p-4">
              <div class="flex items-center">
                <div class="ml-3">
                  <p class="text-sm text-orange-700">
                    您尚未完成实名认证。提交后将自动发起实名认证，信息通过后不可修改。
                  </p>
                </div>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">手机号</label>
              <input
                type="tel"
                :readonly="isPhoneReadonly"
                class="w-full p-3 bg-gray-50 border border-gray-200 rounded-lg text-gray-900"
                v-model="form.phone"
                placeholder="请输入手机号"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">真实姓名</label>
              <input
                v-model="form.realName"
                type="text"
                placeholder="请输入真实姓名"
                class="w-full p-3 border border-gray-200 rounded-lg text-gray-900 bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">证件号码</label>
              <input
                v-model="form.idNumber"
                type="text"
                placeholder="请输入证件号码"
                class="w-full p-3 border border-gray-200 rounded-lg text-gray-900 bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">银行卡号【用于报酬结算】</label>
              <input
                v-model="form.bankCard"
                type="text"
                placeholder="请输入您本人银行卡号码"
                class="w-full p-3 border border-gray-200 rounded-lg text-gray-900 bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <div>
              <button
                type="button"
                class="w-full bg-blue-500 text-white py-3 rounded-lg shadow-sm hover:bg-blue-600 transition-colors disabled:opacity-60"
                @click="handleRealNameVerification"
                :disabled="realNameLoading"
              >
                实名认证
              </button>
            </div>
          </div>
        </div>

        <div
          :class="[
            'collapse rounded-lg',
            shouldOpenStep2 ? 'collapse-open collapse-arrow bg-white' : 'collapse-close bg-gray-100'
          ]"
        >
          <input type="checkbox" class="peer" :checked="shouldOpenStep2" />
          <div class="collapse-title text-base font-medium text-gray-900">
            步骤二：身份证备案
          </div>
          <div
            v-if="shouldOpenStep2"
            class="collapse-content space-y-4"
            :style="{ height: 'fit-content' }"
          >
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">身份证头像面</label>
              <div
                @click="uploadIdCardFront"
                class="w-full aspect-[4/3] border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center cursor-pointer hover:border-gray-400 transition-colors overflow-hidden"
                :class="{ 'border-blue-500 bg-blue-50': form.idCardFront }"
              >
                <div v-if="!form.idCardFront" class="text-center text-gray-500">
                  <svg class="w-12 h-12 mx-auto mb-2" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                  </svg>
                  <p class="text-sm">点击上传身份证头像面</p>
                </div>
                <img v-else :src="form.idCardFront" alt="身份证头像面" class="w-full h-full object-cover rounded-lg" />
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">身份证国徽面</label>
              <div
                @click="uploadIdCardBack"
                class="w-full aspect-[4/3] border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center cursor-pointer hover:border-gray-400 transition-colors overflow-hidden"
                :class="{ 'border-blue-500 bg-blue-50': form.idCardBack }"
              >
                <div v-if="!form.idCardBack" class="text-center text-gray-500">
                  <svg class="w-12 h-12 mx-auto mb-2" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                  </svg>
                  <p class="text-sm">点击上传身份证国徽面</p>
                </div>
                <img v-else :src="form.idCardBack" alt="身份证国徽面" class="w-full h-full object-cover rounded-lg" />
              </div>
            </div>
            <div>
              <button
                type="button"
                class="w-full bg-blue-500 text-white py-3 rounded-lg shadow-sm hover:bg-blue-600 transition-colors disabled:opacity-60"
                @click="handleIdCardVerification"
                :disabled="idCardVerifyLoading"
              >
                身份证备案
              </button>
            </div>
          </div>
        </div>

        <!-- <div
          :class="[
            'collapse rounded-lg',
            isFaceApproved ? 'collapse-close bg-gray-100' : 'collapse-arrow bg-white'
          ]"
        >
          <input type="checkbox" class="peer" :checked="!isFaceApproved" />
          <div class="collapse-title text-base font-medium text-gray-900">
            步骤三：人脸核验
          </div>
          <div v-if="!isFaceApproved" class="collapse-content">
            <button
              type="button"
              class="w-full bg-blue-500 text-white py-3 rounded-lg shadow-sm hover:bg-blue-600 transition-colors disabled:opacity-60"
              @click="handleFaceVerification"
              :disabled="faceVerifyLoading"
            >
              轻松核验
            </button>
          </div>
        </div>

        <div
          :class="[
            'collapse rounded-lg',
            latestApplicationApproved ? 'collapse-close bg-gray-100' : 'collapse-arrow bg-white'
          ]"
        >
          <input type="checkbox" class="peer" :checked="!latestApplicationApproved" />
          <div class="collapse-title text-base font-medium text-gray-900">
            步骤四：补充经验
          </div>
          <div v-if="!latestApplicationApproved" class="collapse-content space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">相关经验（选填）</label>
              <textarea
                v-model="form.experience"
                rows="3"
                placeholder="可填写您的相关项目或工作经历"
                class="w-full p-3 border border-gray-200 rounded-lg text-gray-900 bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              ></textarea>
            </div>
            <div v-if="taskId">
              <button
                type="button"
                class="w-full py-3 px-4 bg-blue-500 text-white font-medium rounded-full hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                :disabled="!canSubmit || taskApplyLoading || latestApplicationApproved"
                @click="handleTaskApply"
              >
                立即报名
              </button>
            </div>
          </div>
        </div>

        <!-- 合作方 -->
        <div class="bg-white rounded-lg p-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">合作方</label>
          <input
            type="text"
            :value="taskInfo?.tenant_name || '—'"
            readonly
            class="w-full p-3 bg-gray-50 border border-gray-200 rounded-lg text-gray-900"
          />
        </div>

        <!-- 服务协议 -->
        <div class="bg-white rounded-lg p-4">
          <div class="flex items-center space-x-3">
            <input
              id="agreement"
              v-model="form.agreeToTerms"
              type="checkbox"
              class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
              :disabled="!canAcceptAgreement"
            />
            <label for="agreement" class="text-sm text-gray-700">
              同意 <a href="/service-agreement" class="text-blue-600 hover:text-blue-500">《服务合作协议》</a>
            </label>
          </div>
        </div>

        <!-- 按钮组 -->
        <div class="space-y-3 pt-4">
          <button
            type="button"
            :disabled="!canSubmit || contractSignLoading"
            @click="handleContractSign"
            class="w-full py-3 px-4 bg-blue-500 text-white font-medium rounded-full hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            立即签署
          </button>
          <button
            type="button"
            @click="skipSigning"
            class="w-full py-3 px-4 bg-transparent text-gray-600 font-medium rounded-full hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors"
          >
            忽略
          </button>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="idCardFrontInput"
      type="file"
      accept="image/*"
      @change="handleIdCardFrontUpload"
      class="hidden"
    />
    <input
      ref="idCardBackInput"
      type="file"
      accept="image/*"
      @change="handleIdCardBackUpload"
      class="hidden"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useApi } from '~/utils/apiConfig'

useHead({
  title: '协议签署'
})

// 表单数据
const form = ref({
  phone: '',
  idCardFront: '',
  idCardBack: '',
  realName: '',
  idNumber: '',
  experience: '',
  bankCard: '',
  agreeToTerms: false
})

const route = useRoute()

const profile = ref(null)
const profileLoaded = ref(false)
const realNameLoading = ref(false)
const idCardVerifyLoading = ref(false)
const faceVerifyLoading = ref(false)
const contractSignLoading = ref(false)
const taskInfo = ref(null)
const taskLoading = ref(false)
const latestApplication = ref(null)
const taskApplyLoading = ref(false)

// API 实例
const api = useApi('freelancer')
const { showSuccess, showError, showInfo } = useToast()

// 获取任务ID（如果是从任务页面跳转过来的）
const taskId = route.query.taskId

// refs
const idCardFrontInput = ref(null)
const idCardBackInput = ref(null)
const idCardFrontFile = ref(null)
const idCardBackFile = ref(null)

const MAX_IMAGE_SIZE_BYTES = 500 * 1024
const IMAGE_TOO_LARGE_MESSAGE = '照片体积过大，请控制在单张500KB以内'
const IMAGE_TOO_LARGE_ERROR = 'PHOTO_TOO_LARGE'
const UNSUPPORTED_IMAGE_MESSAGE = '暂不支持HEIC格式，请转换为JPG或PNG后再上传'
const UNSUPPORTED_IMAGE_ERROR = 'UNSUPPORTED_IMAGE'

// 计算属性
const isVerified = computed(() => profile.value?.verification_status === 'approved')
const isIdCardApproved = computed(() => profile.value?.id_card_recognition_status === 'approved')
const isFaceApproved = computed(() => profile.value?.face_recognition_status === 'approved')
const latestApplicationApproved = computed(() => latestApplication.value?.status === 'approved')
const shouldOpenStep2 = computed(() => isVerified.value && !isIdCardApproved.value)
const canAcceptAgreement = computed(() => isVerified.value && isIdCardApproved.value)
const isPhoneReadonly = ref(false)

const canSubmit = computed(() => {
  if (!profileLoaded.value) return false

  if (isVerified.value) {
    return form.value.agreeToTerms
  }

  const hasName = typeof form.value.realName === 'string' && form.value.realName.trim().length > 0
  const hasId = typeof form.value.idNumber === 'string' && form.value.idNumber.trim().length > 0
  const hasBankCard = typeof form.value.bankCard === 'string' && form.value.bankCard.trim().length > 0

  return hasName &&
         hasId &&
         hasBankCard &&
         form.value.agreeToTerms
})

// 方法
const goBack = () => {
  window.history.back()
}

const initializePhoneReadonly = (phone) => {
  if (isPhoneReadonly.value) return
  if (typeof phone === 'string' && phone.trim().length > 0) {
    isPhoneReadonly.value = true
  }
}

const uploadIdCardFront = () => {
  idCardFrontInput.value?.click()
}

const uploadIdCardBack = () => {
  idCardBackInput.value?.click()
}

const handleIdCardFrontUpload = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    if (isHeicFile(file)) {
      showError(UNSUPPORTED_IMAGE_MESSAGE)
      if (event.target) {
        event.target.value = ''
      }
      return
    }
    idCardFrontFile.value = file
    const reader = new FileReader()
    reader.onload = (e) => {
      form.value.idCardFront = e.target?.result || ''
      recognizeIdCard(file, 'front')
    }
    reader.readAsDataURL(file)
  }
  if (event.target) {
    event.target.value = ''
  }
}

const handleIdCardBackUpload = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    if (isHeicFile(file)) {
      showError(UNSUPPORTED_IMAGE_MESSAGE)
      if (event.target) {
        event.target.value = ''
      }
      return
    }
    idCardBackFile.value = file
    const reader = new FileReader()
    reader.onload = (e) => {
      form.value.idCardBack = e.target?.result || ''
      recognizeIdCard(file, 'back')
    }
    reader.readAsDataURL(file)
  }
  if (event.target) {
    event.target.value = ''
  }
}

const readFileAsDataUrl = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = () => reject(new Error('读取文件失败'))
    reader.readAsDataURL(file)
  })
}

const isHeicFile = (file) => {
  if (!file) return false
  const type = (file.type || '').toLowerCase()
  if (type.includes('heic') || type.includes('heif')) return true
  const name = typeof file.name === 'string' ? file.name.toLowerCase() : ''
  return name.endsWith('.heic') || name.endsWith('.heif')
}

const loadImageElement = (src) => {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.onload = () => resolve(image)
    image.onerror = () => reject(new Error('图片加载失败'))
    image.src = src
  })
}

const canvasToBlob = (canvas, type, quality) => {
  return new Promise((resolve, reject) => {
    if (canvas.toBlob) {
      canvas.toBlob((blob) => {
        if (blob) resolve(blob)
        else reject(new Error('图片压缩失败'))
      }, type, quality)
    } else {
      try {
        const dataUrl = canvas.toDataURL(type, quality)
        resolve(dataUrlToBlob(dataUrl))
      } catch (error) {
        reject(error)
      }
    }
  })
}

const dataUrlToBlob = (dataUrl) => {
  const parts = dataUrl.split(',')
  if (parts.length < 2) {
    throw new Error('无效的图片数据')
  }
  const match = parts[0].match(/:(.*?);/)
  const mime = match ? match[1] : 'image/jpeg'
  const binary = atob(parts[1])
  const len = binary.length
  const array = new Uint8Array(len)
  for (let i = 0; i < len; i++) {
    array[i] = binary.charCodeAt(i)
  }
  return new Blob([array], { type: mime })
}

const dataUrlToFile = (dataUrl, filename) => {
  const blob = dataUrlToBlob(dataUrl)
  if (typeof File === 'function') {
    return new File([blob], filename, { type: blob.type })
  }
  const fallback = blob.slice(0, blob.size, blob.type)
  fallback.name = filename
  return fallback
}

const createFileFromBlob = (blob, originalName, mimeType) => {
  const baseName = originalName ? originalName.replace(/\.[^/.]+$/, '') : 'image'
  const extension = mimeType === 'image/jpeg' ? 'jpg' : mimeType.split('/')[1] || 'jpg'
  const fileName = `${baseName}.${extension}`
  if (typeof File === 'function') {
    return new File([blob], fileName, { type: mimeType })
  }
  const fallback = blob.slice(0, blob.size, mimeType)
  fallback.name = fileName
  return fallback
}

const compressImageFile = async (file, maxBytes) => {
  const dataUrl = await readFileAsDataUrl(file)
  const image = await loadImageElement(dataUrl)

  let width = image.naturalWidth || image.width
  let height = image.naturalHeight || image.height
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  let quality = 0.9
  const minQuality = 0.5
  let attempt = 0

  const render = async () => {
    canvas.width = Math.max(1, Math.round(width))
    canvas.height = Math.max(1, Math.round(height))
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
    return await canvasToBlob(canvas, 'image/jpeg', quality)
  }

  let blob = await render()

  while (blob.size > maxBytes && attempt < 10) {
    attempt += 1
    if (quality > minQuality) {
      quality = Math.max(minQuality, quality - 0.1)
    } else {
      width = Math.max(1, Math.round(width * 0.9))
      height = Math.max(1, Math.round(height * 0.9))
    }
    blob = await render()
  }

  if (blob.size > maxBytes) {
    throw new Error(IMAGE_TOO_LARGE_ERROR)
  }

  return createFileFromBlob(blob, file.name, 'image/jpeg')
}

const calculateDataUrlSize = (dataUrl) => {
  if (!dataUrl) return 0
  const base64 = dataUrl.split(',')[1] || ''
  const padding = (base64.match(/=+$/) || [''])[0].length
  return Math.ceil(base64.length * 3 / 4) - padding
}

const prepareImageForUpload = async (file, dataUrl) => {
  let workingFile = file
  if (!workingFile && dataUrl) {
    workingFile = dataUrlToFile(dataUrl, 'idcard.jpg')
  }

  if (!workingFile) {
    throw new Error('请重新上传身份证照片')
  }

  if (isHeicFile(workingFile)) {
    throw new Error(UNSUPPORTED_IMAGE_ERROR)
  }

  if (typeof dataUrl === 'string' && dataUrl.startsWith('data:image/heic')) {
    throw new Error(UNSUPPORTED_IMAGE_ERROR)
  }

  if (workingFile.size <= MAX_IMAGE_SIZE_BYTES) {
    const base64 = dataUrl || await readFileAsDataUrl(workingFile)
    return { file: workingFile, base64 }
  }

  const base64Size = calculateDataUrlSize(dataUrl)
  if (!file && base64Size && base64Size <= MAX_IMAGE_SIZE_BYTES) {
    return { file: workingFile, base64: dataUrl }
  }

  const compressedFile = await compressImageFile(workingFile, MAX_IMAGE_SIZE_BYTES)
  const base64 = await readFileAsDataUrl(compressedFile)
  return { file: compressedFile, base64 }
}

const recognizeIdCard = async (file, side) => {
  try {
    // 模拟OCR识别
    if (side === 'front') {
      // 模拟识别结果
      setTimeout(() => {
        form.value.realName = '张三'
        form.value.idNumber = '110101199001011234'
      }, 1000)
    }
  } catch (error) {
    console.error('身份证识别失败:', error)
  }
}

const handleRealNameVerification = async () => {
  const name = form.value.realName?.trim()
  const phone = form.value.phone?.trim()
  const idCard = form.value.idNumber?.trim()
  const bankCard = form.value.bankCard?.trim()

  if (!name || !phone || !idCard || !bankCard) {
    showError('请先完整填写实名认证所需信息')
    return
  }

  realNameLoading.value = true

  try {
    const response = await api.post('/profile/real-name-verify', {
      name,
      phone,
      idCard,
      bankCard
    })

    if (response.code === 0) {
      showSuccess(response.message || '实名认证成功')
      if (response.data?.user) {
        profile.value = {
          ...(profile.value || {}),
          ...response.data.user,
        }
      }
    } else {
      showError(response.message || '实名认证失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '实名认证失败'
    showError(message)
  } finally {
    realNameLoading.value = false
  }
}

const handleIdCardVerification = async () => {
  if (!form.value.idCardFront || !form.value.idCardBack) {
    showError('请先上传身份证正反面')
    return
  }

  idCardVerifyLoading.value = true

  let processedFront
  let processedBack

  try {
    processedFront = await prepareImageForUpload(idCardFrontFile.value, form.value.idCardFront)
    processedBack = await prepareImageForUpload(idCardBackFile.value, form.value.idCardBack)
  } catch (error) {
    idCardVerifyLoading.value = false
    let message
    if (error?.message === IMAGE_TOO_LARGE_ERROR) {
      message = IMAGE_TOO_LARGE_MESSAGE
    } else if (error?.message === UNSUPPORTED_IMAGE_ERROR) {
      message = UNSUPPORTED_IMAGE_MESSAGE
    } else {
      message = error?.message || '身份证识别失败'
    }
    showError(message)
    return
  }

  form.value.idCardFront = processedFront.base64
  form.value.idCardBack = processedBack.base64
  idCardFrontFile.value = processedFront.file
  idCardBackFile.value = processedBack.file

  try {
    const response = await api.post('/profile/id-card-ocr', {
      frontImage: form.value.idCardFront,
      backImage: form.value.idCardBack
    })

    if (response.code === 0) {
      showSuccess(response.message || '身份证识别成功')

      const front = response.data?.front
      if (front?.success && front.data) {
        form.value.realName = front.data.name || form.value.realName
        form.value.idNumber = front.data.idNumber || form.value.idNumber
      }

      await loadProfile()
    } else {
      showError(response.message || '身份证识别失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '身份证识别失败'
    showError(message)
  } finally {
    idCardVerifyLoading.value = false
  }
}

const handleFaceVerification = async () => {
  faceVerifyLoading.value = true

  try {
    const response = await api.post('/profile/face-recognition', {
      returnUrl: `${window.location.origin}/contracts`
    })
    console.log(response.data)
    if (response.code === 0) {
      const redirectUrl = response.data?.startFaceUrl || response.data?.url
      if (redirectUrl) {
        if (profile.value) {
          profile.value.face_recognition_status = 'pending'
        }
        window.location.href = redirectUrl
      } else {
        showError('未获取到人脸核验链接')
      }
    } else {
      if (profile.value) {
        profile.value.face_recognition_status = 'rejected'
      }
      showError(response.message || '人脸核验链接获取失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '人脸核验失败'
    if (profile.value) {
      profile.value.face_recognition_status = 'rejected'
    }
    showError(message)
  } finally {
    faceVerifyLoading.value = false
  }
}

const handleContractSign = async () => {
  if (!taskId) {
    showError('缺少任务信息，无法签署')
    return
  }

  if (!canSubmit.value) {
    showError('请先完成必要信息并同意协议')
    return
  }

  contractSignLoading.value = true

  try {
    const response = await api.post('/sign-contract', {
      taskId,
      returnUrl: window.location.href
    })

    if (response.code === 0) {
      const shortUrl = response.data?.shortUrl
      if (shortUrl) {
        window.location.href = shortUrl
        return
      }
      showError('未获取到签署链接')
    } else {
      showError(response.message || '签署失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '签署失败，请重试'
    showError(message)
  } finally {
    contractSignLoading.value = false
  }
}

const handleTaskApply = async () => {
  if (!taskId) {
    showError('缺少任务信息，无法报名')
    return
  }

  if (!canSubmit.value) {
    showError('请先完成必要信息并同意协议')
    return
  }

  taskApplyLoading.value = true

  try {
    const requestData = {
      taskId,
      experience: typeof form.value.experience === 'string' ? form.value.experience.trim() : ''
    }

    if (!isVerified.value) {
      if (!form.value.idCardFront || !form.value.idCardBack) {
        showError('请先上传身份证正反面')
        taskApplyLoading.value = false
        return
      }

      let processedFront
      let processedBack

      try {
        processedFront = await prepareImageForUpload(idCardFrontFile.value, form.value.idCardFront)
        processedBack = await prepareImageForUpload(idCardBackFile.value, form.value.idCardBack)
      } catch (error) {
        let message
        if (error?.message === IMAGE_TOO_LARGE_ERROR) {
          message = IMAGE_TOO_LARGE_MESSAGE
        } else if (error?.message === UNSUPPORTED_IMAGE_ERROR) {
          message = UNSUPPORTED_IMAGE_MESSAGE
        } else {
          message = error?.message || '身份证照片处理失败'
        }
        showError(message)
        taskApplyLoading.value = false
        return
      }

      form.value.idCardFront = processedFront.base64
      form.value.idCardBack = processedBack.base64
      idCardFrontFile.value = processedFront.file
      idCardBackFile.value = processedBack.file

      const name = typeof form.value.realName === 'string' ? form.value.realName.trim() : ''
      const idCard = typeof form.value.idNumber === 'string' ? form.value.idNumber.trim() : ''
      const bankCard = typeof form.value.bankCard === 'string' ? form.value.bankCard.trim() : ''

      Object.assign(requestData, {
        name,
        idCard,
        bankCard,
        idCardFront: form.value.idCardFront,
        idCardBack: form.value.idCardBack,
      })
    }

    const response = await api.post('/apply-task', requestData)

    if (response.code === 0) {
      showSuccess(response.message || '报名成功，请等待审核结果')
      await loadLatestApplication()
      await navigateTo('/contracts')
    } else {
      showError(response.message || '报名失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '报名失败，请重试'
    showError(message)
  } finally {
    taskApplyLoading.value = false
  }
}

const skipSigning = async () => {
  await navigateTo('/')
}

// 页面加载时获取用户手机号
onMounted(() => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    const user = JSON.parse(userInfo)
    form.value.phone = user.phone || ''
    initializePhoneReadonly(user.phone)
  }

  loadProfile()
  loadTask()
  loadLatestApplication()
})

watch(profileLoaded, (loaded) => {
  if (!loaded) return

  const method = route.query?.method
  const dataParam = route.query?.data

  if (method === 'h5.face.notify' && dataParam) {
    try {
      const parsed = JSON.parse(dataParam)
      if (parsed && typeof parsed === 'object' && parsed.msg) {
        showInfo(`人脸识别结果：${parsed.msg}`)
      }
    } catch (error) {
      showError('人脸识别结果解析失败')
    }
  }
})

const loadProfile = async () => {
  try {
    const response = await api.get('/profile')
    if (response.code === 0 && response.data) {
      profile.value = response.data
    }
  } catch (error) {
    console.error('获取用户资料失败:', error)
  } finally {
    profileLoaded.value = true
  }
}

const loadTask = async () => {
  if (!taskId) return

  taskLoading.value = true
  try {
    const response = await api.get(`/tasks/${taskId}`)
    if (response.code === 0) {
      taskInfo.value = response.data
    } else {
      showError(response.message || '任务信息获取失败')
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '任务信息获取失败'
    showError(message)
  } finally {
    taskLoading.value = false
  }
}

const loadLatestApplication = async () => {
  if (!taskId) return

  try {
    const response = await api.get(`/tasks/${taskId}/latest-application`)
    if (response.code === 0) {
      latestApplication.value = response.data
    }
  } catch (error) {
    const message = error?.response?.data?.message || error?.message || '报名状态获取失败'
    showError(message)
  }
}

watch(profile, (value) => {
  if (!value) return

  if (value.phone) {
    form.value.phone = value.phone
    initializePhoneReadonly(value.phone)
  }

  const profileName = value.real_name || value.name || ''

  if (value.verification_status === 'approved') {
    form.value.realName = profileName
    form.value.idNumber = value.id_card || ''
    form.value.bankCard = value.bank_account || ''
  } else {
    if (profileName) form.value.realName = profileName
    if (value.id_card) form.value.idNumber = value.id_card
    if (value.bank_account) form.value.bankCard = value.bank_account
  }
}, { immediate: true })
</script>
